package com.bracelet.util;


import lombok.extern.slf4j.Slf4j;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuples;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.regex.Pattern;

/*
* 工具格式化手环输入信息类
* */
@Slf4j
public class MessageFormatUtil {
    /**
     * 检查数据格式是否合规 该协议中所有数据都按照[厂商*设备 ID*内容长度*内容]格式
     * */
    public static Tuple3<Boolean, String,String> checkMsg(String msg){
        String regex1 = "\\[.*?\\].*";
        String bizkey = "";
        boolean flag = true;
        String serviceId = "";
        try{
            if(Pattern.matches(regex1, msg)){
                // 格式无误后 处理字符串获取唯一设备ID作为bizkey
                String[] titleMessage = msg.split("[*]");
                bizkey = titleMessage[1];
                serviceId = titleMessage[3].split(",")[0];
            }
        }catch (Exception e){
            flag = false;
            log.error("字段格式处理异常，请求信息:{}格式不合规！"+msg);
            e.printStackTrace();
        }
        return  Tuples.of(flag, bizkey,serviceId);
    }



    // 格式化实体类保存
    public static Object formateObj(String [] args,String className) throws  Exception{
        int i = 0;
        Class<?> aClass = Class.forName(className);
        Object instance = aClass.newInstance();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            // serialVersionUID  id inputtime updatetime 固定字段不处理
            if("serialVersionUID".equals(name)||"inputtime".equals(name)||"updatetime".equals(name)||"id".equals(name)){
                continue;
            }
            String getMethodName = "set" + name.substring(0, 1).toUpperCase(Locale.ROOT) + name.substring(1);
                Method method = aClass.getMethod(getMethodName,String.class);
                Object invoke = method.invoke(instance,args[i]);
                if(i == args.length-1){
                    break;
                }else {
                    i++;
                }
        }
        return instance;
    }
}
